package org.example.innovate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.innovate.common.CommonResponse;
import org.example.innovate.domain.Dish;
import org.example.innovate.domain.Follow;
import org.example.innovate.domain.User;
import org.example.innovate.mapper.DishMapper;
import org.example.innovate.mapper.UserMapper;
import org.example.innovate.service.FollowService;
import org.example.innovate.mapper.FollowMapper;
import org.example.innovate.util.JwtUtil;
import org.example.innovate.vo.DishOneVo;
import org.example.innovate.vo.FollowVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【follow】的数据库操作Service实现
* @createDate 2025-03-13 17:00:29
*/
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>
    implements FollowService{
    @Resource
    private FollowMapper followMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DishMapper dishMapper;

    @Override
    @Transactional
    public void follow(Integer followerId, Integer followedId) {
        // 验证被关注用户是否存在
        if (userMapper.selectById(followedId) == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查是否已关注
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowerId, followerId)
                .eq(Follow::getFollowedId, followedId);

        if (followMapper.exists(queryWrapper)) {
            throw new RuntimeException("已关注该用户");
        }

        Follow follow = new Follow();
        follow.setFollowerId(followerId);
        follow.setFollowedId(followedId);
        followMapper.insert(follow);
    }

    @Override
    @Transactional
    public void unfollow(Integer followerId, Integer followedId) {
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowerId, followerId)
                .eq(Follow::getFollowedId, followedId);

        if (followMapper.delete(queryWrapper) == 0) {
            throw new RuntimeException("未关注该用户");
        }
    }

    @Override
    public Page<FollowVo> getFanList(Integer currentUserId, Integer page) {
        // 1. 设置分页参数
        Page<Follow> pageParam = new Page<>(page, 10);

        // 2. 查询粉丝列表（关注当前用户的用户）
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowedId, currentUserId)
                .orderByDesc(Follow::getCreatedAt);
        followMapper.selectPage(pageParam, queryWrapper);

        if (pageParam.getRecords().isEmpty()) {
            return new Page<>(page, 10);
        }

        // 3. 提取粉丝ID列表
        List<Integer> fanIds = pageParam.getRecords().stream()
                .map(Follow::getFollowerId)
                .collect(Collectors.toList());

        // 4. 批量查询用户信息
        List<User> users = userMapper.selectBatchIds(fanIds);

        // 5. 查询当前用户的关注列表（优化为只查询一次）
        Set<Integer> followingIds = getFollowingIds(currentUserId);

        // 6. 转换为VO对象
        return (Page<FollowVo>) pageParam.convert(follow -> {
            User user = users.stream()
                    .filter(u -> u.getUserId().equals(follow.getFollowerId()))
                    .findFirst()
                    .orElse(null);

            if (user == null) return null;

            boolean isFollowing = followingIds.contains(user.getUserId());
            boolean mutual = isFollowing; // 互相关注 = 粉丝关注当前用户 + 当前用户关注粉丝

            FollowVo followVo = new FollowVo(user.getUserId(),
                    user.getUsername(),
                    user.getProfilePicture());
            followVo.setIsFollowing(isFollowing);
            followVo.setMutual(mutual);
            return followVo;
        });
    }

    // 获取当前用户关注的所有用户ID（使用缓存优化）
    private Set<Integer> getFollowingIds(Integer currentUserId) {
        LambdaQueryWrapper<Follow> query = new LambdaQueryWrapper<>();
        query.select(Follow::getFollowedId)
                .eq(Follow::getFollowerId, currentUserId);
        return followMapper.selectList(query)
                .stream()
                .map(Follow::getFollowedId)
                .collect(Collectors.toSet());
    }

    @Override
    public Page<FollowVo> getFollowList(Integer followerId, Integer page) {
        // 1. 设置分页参数（每页10条）
        Page<Follow> pageParam = new Page<>(page, 10);

        // 2. 查询关注关系
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowerId, followerId)
                .orderByDesc(Follow::getCreatedAt);

        followMapper.selectPage(pageParam, queryWrapper);

        // 3. 没有数据直接返回空
        if (pageParam.getRecords().isEmpty()) {
            return new Page<>(page, 10);
        }

        // 4. 获取被关注用户ID列表
        List<Integer> followedIds = pageParam.getRecords().stream()
                .map(Follow::getFollowedId)
                .collect(Collectors.toList());

        // 5. 查询用户详细信息
        List<User> users = userMapper.selectBatchIds(followedIds);

        // 6. 转换为VO对象
        return (Page<FollowVo>) pageParam.convert(follow -> {
            User user = users.stream()
                    .filter(u -> u.getUserId().equals(follow.getFollowedId()))
                    .findFirst()
                    .orElse(null);

            if (user != null) {
                return new FollowVo(
                        user.getUserId(),
                        user.getUsername(),
                        user.getProfilePicture()
                        // 其他需要返回的字段...
                );
            }
            return null;
        });


    }

    @Override
    public CommonResponse<List<DishOneVo>> getAll(HttpServletRequest request)
    {
        String token=request.getHeader("token");
        System.out.println(token);
        JwtUtil.verifyToken(token);
        User user= JwtUtil.getCurrentUser(token);
        if(user==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follower_id", user.getUserId());
        List<Follow> follows = followMapper.selectList(queryWrapper);
        List<Integer> ids=new ArrayList<>();
        for(Follow follow:follows)
        {
            ids.add(follow.getFollowedId());
        }
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.in("user_id", ids);
        dishQueryWrapper.orderByDesc("created_at");
        List<Dish> dishes=dishMapper.selectList(dishQueryWrapper);
        List<DishOneVo> dishOneVos=new ArrayList<>();
        for(Dish dish:dishes)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",dish.getUserId());
            user=userMapper.selectOne(userQueryWrapper);
            DishOneVo dishOneVo=new DishOneVo();
            dishOneVo.setUsername(user.getUsername());
            Calendar cal = Calendar.getInstance();
            cal.setTime(dish.getCreatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            Date eightHoursAgo = cal.getTime();
            dish.setCreatedAt(eightHoursAgo);
            cal.setTime(dish.getUpdatedAt());
            cal.add(Calendar.HOUR_OF_DAY, 8);
            eightHoursAgo = cal.getTime();
            dish.setUpdatedAt(eightHoursAgo);
            dishOneVo.setDish(dish);
            dishOneVos.add(dishOneVo);
        }
        return CommonResponse.createForSuccess("查询成功",dishOneVos);
    }
}




